package com.snnsh.kjb.lottery.dao;

import com.snnsh.kjb.lottery.po.LotteryRecordPO;
import com.snnsh.kjb.lottery.po.ProductPO;
import com.snnsh.kjb.lottery.util.Dom4jXMLManager;
import com.snnsh.kjb.lottery.util.TimeUtil;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * packageName com.snnsh.kjb.lottery.dao
 *
 * @author wick
 * @version V1.0.0
 * @date 2025/5/27
 */

@Repository
public class LotteryRecordByXmlDao implements ILotteryRecordDao{

    private static final String XML_LOTTERY_RECORD_FILENAME ="LotteryRecords.xml";

    @Override
    public void addLotteryRecord(ProductPO product) {
        LotteryRecordPO lotteryRecordPO = new LotteryRecordPO();
        lotteryRecordPO.setPid(product.getId());
        lotteryRecordPO.setPname(product.getName());
        lotteryRecordPO.setDatetime(TimeUtil.getDatetimeString());
        List<LotteryRecordPO> list = Dom4jXMLManager.getFromXML(XML_LOTTERY_RECORD_FILENAME, LotteryRecordPO.class);
        list.add(lotteryRecordPO);
        Dom4jXMLManager.write2Xml(list,LotteryRecordPO.class,XML_LOTTERY_RECORD_FILENAME);
    }

    @Override
    public List<LotteryRecordPO> list(String prodName) {
        List<LotteryRecordPO> list = Dom4jXMLManager.getFromXML(XML_LOTTERY_RECORD_FILENAME, LotteryRecordPO.class);
        if(ObjectUtils.isEmpty(prodName)){
            return list;
        }
        else {
            list = list.stream().filter(v->{
                if(v.getPname().contains(prodName)){
                    return true;
                }
                else {
                    return false;
                }
            }).collect(Collectors.toList());
        }
        return list;
    }

    public static void main(String[] args) {
        ProductByXmlDao productByXmlDao = new ProductByXmlDao();
        List<ProductPO> list = productByXmlDao.list(null);
        //productByXmlDao.addProduct(new ProductPO("小米手眼",20F,1));
        System.out.println(list);
        ProductPO productPO = list.get(0);
        //添加记录
        LotteryRecordByXmlDao lotteryRecordByXmlDao = new LotteryRecordByXmlDao();
        //查询原有记录
        System.out.println(lotteryRecordByXmlDao.list(null));
        lotteryRecordByXmlDao.addLotteryRecord(productPO);
        List<LotteryRecordPO> list1 = lotteryRecordByXmlDao.list(null);
        System.out.println(list1);
    }

    @Override
    public void clearLotteryRecord() {
        Dom4jXMLManager.write2Xml(Collections.EMPTY_LIST,LotteryRecordPO.class,XML_LOTTERY_RECORD_FILENAME);
    }
}
